package com.ffcs.web.services;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffcs.web.controllers.FreeAskController;
import com.ffcs.web.daos.implementations.CounselorDao;
import com.ffcs.web.daos.implementations.DirectionDao;
import com.ffcs.web.daos.implementations.FreeAskDao;
import com.ffcs.web.model.dto.OrderPing;
import com.ffcs.web.model.entity.Counselor;
import com.ffcs.web.model.entity.Direction;
import com.ffcs.web.model.entity.FreeAsk;
import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.utils.ChinaeseUtil;
import com.ffcs.web.utils.CommonConfig;
import com.ffcs.web.utils.JsSign;

@Service
public class FreeAskService {

	@Autowired
	private FreeAskDao freeAskDao;
	@Autowired
	private DirectionDao directionDao;
	@Autowired
	private CounselorDao counselorDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	private Logger logger = Logger.getLogger(FreeAskService.class);
	
	/**
	 * 保存询问
	 * @param wxUser
	 * @param direction
	 * @param question
	 * @param type
	 */
	@Transactional
	public FreeAsk addFreeAsk(WxUser wxUser, String direction, String question,
			String type) {
		FreeAsk freeAsk=new FreeAsk();
		if(type.equals("0")){
			question=ChinaeseUtil.CharTOChinaese(question);
		}else{
			//wxLocalResource://
			question=question.replace("wxLocalResource://", "");
		}
		if(direction.equals("1")){
			freeAsk.setDirection("学业倦怠");
		}
		if(direction.equals("2")){
			freeAsk.setDirection("亲子关系");
		}
		if(direction.equals("3")){
			freeAsk.setDirection("教育理念");
		}
		if(direction.equals("4")){
			freeAsk.setDirection("学习习惯");
		}
		if(direction.equals("5")){
			freeAsk.setDirection("人际关系");
		}
		if(direction.equals("6")){
			freeAsk.setDirection("沉迷网络");
		}
		if(direction.equals("7")){
			freeAsk.setDirection("情绪管理");
		}
		if(direction.equals("8")){
			freeAsk.setDirection("自控能力");
		}
		freeAsk.setQuestion(question);
		freeAsk.setAskTime(new Date());
		freeAsk.setUserId(wxUser.getId());
		freeAsk.setStatus((short)0);
		freeAsk.setIsLoad((short)0);
		freeAsk.setType(Short.parseShort(type));
		List<Counselor> counselorList=counselorDao.findByPropertyName("counseStatus",(short)1);
		List<String> counseTelList=new ArrayList<String>();
		for (Counselor counselor : counselorList) {
			if(counselor.getGoodDirection().contains(direction) && counselor.getIsFreeAsk()==1){
				counseTelList.add(counselor.getCounseTel());
			}
		}
		if(counseTelList.size()==1){
			logger.info("唯一随机分配咨询师"+counseTelList.get(0));
			freeAsk.setAskCounseTel(counseTelList.get(0));
		}else if(counseTelList.size()>0){
			int max=counseTelList.size()-1;
	        int min=0;
	        Random random = new Random();
	        int s = random.nextInt(max)%(max-min+1) + min;
	        logger.info("随机分配咨询师"+counseTelList.get(s));
	        freeAsk.setAskCounseTel(counseTelList.get(s));
		}else{
			logger.info("提交问题匹配不到相关咨询师，默认为123456789");
			freeAsk.setAskCounseTel("123456789");
		}
		
		freeAskDao.save(freeAsk);
		return freeAsk;
	}

	/**
	 * 获取我的提问
	 * @param id
	 * @return
	 */
	public List<FreeAsk> getFreeAsk(Integer id) {
		List<FreeAsk> freeAskList=freeAskDao.findByPropertyNameWithOrder("userId",id,"askTime", false);
		return freeAskList;
	}
	
	/**
	   * 获取媒体文件
	   * @param accessToken 接口访问凭证
	   * @param media_id 媒体文件id
	   * @param savePath 文件在服务器上的存储路径
	   * */
	  public static String downloadMedia(String accessToken, String mediaId, String savePath) {
	    String filePath = null;
	    // 拼接请求地址
	    String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	    requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
	    System.out.println(requestUrl);
	    try {
	      URL url = new URL(requestUrl);
	      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	      conn.setDoInput(true);
	      conn.setRequestMethod("GET");

	      if (!savePath.endsWith("/")) {
	        savePath += "/";
	      }
	      // 根据内容类型获取扩展名
	      String fileExt = ".amr";
	      // 将mediaId作为文件名
	      filePath = savePath + new Date().getTime() + fileExt;

	      BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
	      FileOutputStream fos = new FileOutputStream(new File(filePath));
	      byte[] buf = new byte[8096];
	      int size = 0;
	      while ((size = bis.read(buf)) != -1)
	        fos.write(buf, 0, size);
	      fos.close();
	      bis.close();

	      conn.disconnect();
	      String info = String.format("下载媒体文件成功，filePath=" + filePath);
	      System.out.println(info);
	    } catch (Exception e) {
	      filePath = null;
	      String error = String.format("下载媒体文件失败：%s", e);
	      System.out.println(error);
	    }
	    return filePath;
	  }
	  
	  public static String main1(String token,String serverId,String path) {
		String filePath=downloadMedia(token, serverId,path);
		System.out.println(filePath);
		  File source = new File(filePath);
		  String newMp3Name=new Date().getTime()+".mp3";
			File target = new File(path+newMp3Name);
		  try {
			main2(source,target);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  return newMp3Name;
	  }
	  
  public static void main2(File source,File target) throws Exception {
//		File source = new File("C:\\test3.amr");
//		File target = new File("C:\\test3.mp3");
		AudioAttributes audio = new AudioAttributes();
		Encoder encoder = new Encoder();
		
		// pcm_s16le libmp3lame libvorbis libfaac
		audio.setCodec("libmp3lame");
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);
		
		encoder.encode(source, target, attrs);
	}
  
  public static void main(String[] args) {
	  main1(JsSign.getAccessToken(), "tI89HYLwIZbuVo9nAFUHXwsZDMzPhnCXukYmQ1zZM-OqtlTIEwVlGwQmxf2LWf0a","G://ffcs/apache-tomcat-x64/apache-tomcat-7.0.52/webapps/Counseling");
}
  
	@Transactional
	public void saveFreeAsk(FreeAsk freeAsk) {
		freeAskDao.save(freeAsk);
	}

	@Transactional
	public void deleteFreeAsk(String deleteId) {
		freeAskDao.removeById(Integer.parseInt(deleteId));
	}

	public List<FreeAsk> getFreeAskList(String counseTel) {
		List<FreeAsk> freeAskList=freeAskDao.findByPropertyNameWithOrder("askCounseTel",counseTel,"askTime", false);
		return freeAskList;
	}

	public FreeAsk getFreeAskDesc(int askId) {
		return freeAskDao.get(askId);
	}
	
	@Transactional
	public FreeAsk updateFreeAsk(String askId, String question) {
		FreeAsk freeAsk=freeAskDao.get(Integer.parseInt(askId));
		freeAsk.setCounseAnswer(ChinaeseUtil.CharTOChinaese(question));
		freeAsk.setCounseAskTime(new Date());
		freeAsk.setStatus((short)1);
		freeAskDao.save(freeAsk);
		return freeAsk;
	}

	public List<FreeAsk> gotoMyAskAnswer(String askId) {
		return null;
	}

	/**
	 * 更新提问的评价
	 * @param askId
	 * @param pingjiaxx
	 * @param pingjia
	 */
	@Transactional
	public void gotoPingjiaAsk(String askId, String pingjiaxx, String pingjia) {
		FreeAsk freeAsk=freeAskDao.get(Integer.parseInt(askId));
		freeAsk.setPingjia(ChinaeseUtil.CharTOChinaese(pingjia));
		freeAsk.setPingjiaxx(pingjiaxx);
		freeAsk.setPingjiaTime(new Date());
		freeAsk.setStatus((short)2);
		freeAskDao.save(freeAsk);
	}

	public List<FreeAsk> getFreeAskPingjiaList(String tel) {
		String sql="select * from wechat_freeAsk where (status=1 or status=2) and askCounseTel='"+tel+"' order by counseAskTime desc";
		System.out.println(sql);
		return jdbcTemplate.query(sql, new BeanPropertyRowMapper<FreeAsk>(FreeAsk.class));
	}
}
